package com.m3958.logcollector.datacommons.convert;

import java.io.IOException;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import com.google.common.io.ByteStreams;

/**
 * @author jianglibo@gmail.com
 *         2015年11月2日
 *
 */
public class StreamableConvert extends AbstractHttpMessageConverter<Streamable> {
    
    public StreamableConvert() {
        super(MediaType.ALL);
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.http.converter.AbstractHttpMessageConverter#supports(java.lang.Class)
     */
    @Override
    protected boolean supports(Class<?> clazz) {
        return Streamable.class.isAssignableFrom(clazz);
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.http.converter.AbstractHttpMessageConverter#readInternal(java.lang.Class, org.springframework.http.HttpInputMessage)
     */
    @Override
    protected Streamable readInternal(Class<? extends Streamable> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.http.converter.AbstractHttpMessageConverter#writeInternal(java.lang.Object, org.springframework.http.HttpOutputMessage)
     */
    @Override
    protected void writeInternal(Streamable t, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        outputMessage.getHeaders().setContentLength(t.getLength());
        outputMessage.getHeaders().setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ByteStreams.copy(t.getInputStream(), outputMessage.getBody());
    }

}
